from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from utils.response import APIResponse
from . import serializers, models
from libs.iPay.pay import alipay
from libs.iPay.setting import GATEWAY
from django.conf import settings

import time

class OrderPayAPIView(APIView):

    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):

        serializer = serializers.OrderModelSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        subject = serializer.validated_data.get('subject')
        course_query = serializer.validated_data.get('course_query')
        total_amount = float(serializer.validated_data.get('total_amount'))
        out_trade_no = 'luffy_'+str(int(time.time()))

        order_obj = models.Order.objects.create(
            subject=subject,
            total_amount=total_amount,
            out_trade_no=out_trade_no,
            user=request.user
        )

        pay_url = alipay.api_alipay_trade_page_pay(
            subject=order_obj.subject,
            out_trade_no=order_obj.out_trade_no,
            total_amount=order_obj.total_amount,
            return_url=settings.PAY_RETURN_URL,
            notify_url=settings.PAY_NOTIFY_URL,
            timeout_express = settings.PAY_EXP,
        )

        order_detail_ls = [models.OrderDetail(
            order=order_obj,
            course=course,
            price=course.price,
            real_price=course.price
        ) for course in course_query]

        models.OrderDetail.objects.bulk_create(order_detail_ls)

        return APIResponse(results=GATEWAY + pay_url)


class OrderPaySuccessPayAPIView(APIView):

    def post(self, request, *args, **kwargs):
        # charset=utf-8&out_trade_no=luffy_1575715477&method=alipay.trade.page.pay.return&total_amount=99.00&sign=Id07cuH2ItcNjXechs4Nkw57o22yWuWlB824GMxUC9I%2FGpFUUDNrgbthDzM48zZoQyIvoTmQpPMiAkglvMDzitx5oVfJYqfeBdIXnSijXlDR8n87OweJMynSIvnYLODEf0xg0rBETrCz7Kd3Zf25OgXMwDKMk9XHMNniK85L1d3fFc3wRAIhA5R9wL%2FRXrAaw7EuhzDAHWCkwHR5S3qVE1yVfAg%2F14086Njb0QV6LU8uWaFzzovDkvtoohD3Ee8TwGGf3cEHmUsDWw2wlJ2pLEQ7SkjEuTy1g5yBTlDr%2B6guf%2F%2BFdfgozoNlkcDbGTVE2dEqM03cTrHfav6Lgv2vrA%3D%3D&trade_no=2019120722001421121000086068&auth_app_id=2016101500694842&version=1.0&app_id=2016101500694842&sign_type=RSA2&seller_id=2088102179735780&timestamp=2019-12-07%2018%3A44%3A57
        out_trade_no = request.data.get('out_trade_no')
        trade_no = request.data.get('trade_no')
        timestamp = request.data.get('timestamp')
        order_obj = models.Order.objects.filter(out_trade_no=out_trade_no).update(
            trade_no=trade_no,
            timestamp=timestamp,
            order_status=1
        )
        return Response('success')